package com.heima.wemedia.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.heima.common.dtos.PageResult;
import com.heima.common.enums.AppHttpCodeEnum;
import com.heima.common.exception.LeadException;
import com.heima.common.threadlocal.UserThreadLocalUtils;
import com.heima.file.service.MinioService;
import com.heima.model.media.dtos.WmMaterialDto;
import com.heima.wemedia.entity.WmMaterial;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.service.WmMaterialService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Date;
import java.util.UUID;

/**
 * <p>
 * 自媒体图文素材信息表 服务实现类
 * </p>
 *
 * @author RMY
 * @since 2021-11-24
 */
@Slf4j
@Service
public class WmMaterialServiceImpl extends ServiceImpl<WmMaterialMapper, WmMaterial> implements WmMaterialService {
    @Autowired
    private MinioService minioService;
    /**
     * 上传文章素材
     * @param multipartFile
     * @return
     */
    @Override
    public String uploadPicture(MultipartFile multipartFile) {
        //1.解析参数,获得线程用户id
        Integer userId = UserThreadLocalUtils.getUserId();
        if (userId == null || userId == 0){
            throw new LeadException(AppHttpCodeEnum.NEED_LOGIN);
        }
        //获取文件名，并进行改造
        String preFileName = StringUtils.substringAfterLast(multipartFile.getOriginalFilename(),".");
        String newFileName = UUID.randomUUID().toString()+preFileName;
        //上传
        try {
            String url = minioService.uploadImgFile("", newFileName, multipartFile.getInputStream());
            //2.封装WmMaterial
            WmMaterial wmMaterial = new WmMaterial();
            wmMaterial.setUrl(url);
            wmMaterial.setUserId(userId);
            wmMaterial.setType(0);
            wmMaterial.setIsCollection(false);
            wmMaterial.setCreatedTime(new Date());
            boolean b = save(wmMaterial);
            if (!b){
                throw new LeadException(AppHttpCodeEnum.SERVER_ERROR);
            }
            return url;
        } catch (IOException e) {
            log.error("上传失败");
            e.printStackTrace();
            throw new LeadException(AppHttpCodeEnum.UPLOAD_ERROR);
        }

    }
    /**
     * 分页查询素材信息
     * @param dto
     * @return
     */
    @Override
    public PageResult<WmMaterial> findByPage(WmMaterialDto dto) {
       //1.创建查询条件，获取用户id
        Integer userId = UserThreadLocalUtils.getUserId();
        QueryWrapper<WmMaterial> qw = new QueryWrapper<>();
        qw.lambda().eq(WmMaterial::getUserId,userId);
        if (dto.getIsCollection()!=null && dto.getIsCollection() == 1){
            qw.lambda().eq(WmMaterial::getIsCollection,dto.getIsCollection());
        }
        //1.1日期排序
        qw.lambda().orderByDesc(WmMaterial::getCreatedTime);
        //2.创建分页对象
        IPage<WmMaterial> page = new Page<>(dto.getPage(), dto.getSize());
        IPage<WmMaterial> iPage = this.page(page, qw);
        if (iPage == null || CollectionUtils.isEmpty(iPage.getRecords())){
            throw new LeadException(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        //3.返回结果
        return new PageResult<>(dto.getPage(),dto.getSize(),iPage.getTotal(),iPage.getRecords());
    }
}
